package com.mali.malibackendproduct.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mali.backendcommon.common.Result;
import com.mali.backendcommon.util.UserContext;
import com.mali.malibackendmodel.dto.ScratchpadDTO;
import com.mali.malibackendmodel.vo.ScratchpadVO;
import com.mali.malibackendproduct.mapper.ScratchpadMapper;
import com.mali.malibackendmodel.pojo.Scratchpad;
import com.mali.malibackendproduct.service.ScratchpadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @Author:吴键霏
 * @Date：2024/6/16 10:28
 * @Version 1.0
 */
@Service
public class ScratchpadServiceImpl extends ServiceImpl<ScratchpadMapper, Scratchpad> implements ScratchpadService {

    @Autowired
    private ScratchpadMapper scratchpadMapper;

    @Override
    public Result addOrUpdateScratchpadService(ScratchpadDTO scratchpadDTO) {
        //id只与当前用户id有关，不存在外界干扰
        Scratchpad scratchpad = getByUserId(UserContext.getUser().getId());
        if (scratchpad == null) {
            scratchpad = new Scratchpad();
            scratchpad.setUserid(UserContext.getUser().getId());
            scratchpad.setCreateTime(LocalDateTime.now());
            scratchpad.setData(JSONUtil.toJsonStr(scratchpadDTO));
            scratchpad.setCreateTime(LocalDateTime.now());
            save(scratchpad);
        } else {
            scratchpad.setData(JSONUtil.toJsonStr(scratchpadDTO));
            updateById(scratchpad);
        }
        System.out.println(scratchpadDTO.toString());
        System.out.println(scratchpad.toString());
        return Result.success();
    }

    @Override
    public Scratchpad getByUserId(Long userId) {
        QueryWrapper<Scratchpad> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId);
        return scratchpadMapper.selectOne(queryWrapper);
    }

    @Override
    public Result<ScratchpadVO> getScratchpadByUserId() {
        Scratchpad scratchpad=getByUserId(UserContext.getUser().getId());
        if(scratchpad==null){
            return Result.success(new ScratchpadVO());
        }else {
            return Result.success(JSONUtil.toBean(scratchpad.getData(),ScratchpadVO.class));
        }
    }

    @Override
    public Result deleteScratchpadByUserId() {
        Scratchpad scratchpad=getByUserId(UserContext.getUser().getId());
        removeById(scratchpad);
        return Result.success();
    }
}
